package com.shycloud.mido.member.api.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Xiaoxing Yu
 * @date 2020/10/13
 **/
@Slf4j
@Configuration
@AllArgsConstructor
public class FeignConfig implements RequestInterceptor {

	private final RedisTemplate redisTemplate;

	@Override
	public void apply(RequestTemplate requestTemplate) {

		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (Objects.nonNull(attributes)) {
			HttpServletRequest request = attributes.getRequest();
//			String token = request.getHeader(HttpHeaders.AUTHORIZATION);
			Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
			if (!(authentication instanceof OAuth2Authentication)) {
				String tokenVal = (String)redisTemplate.opsForValue().get("valid_token");
				requestTemplate.header(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", tokenVal));
			} else {
				OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
				requestTemplate.header(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", details.getTokenValue()));
			}
		}
		
	}

}
